import { makeAutoObservable } from 'mobx';
import { Role,RoleFormValues} from './types';
import { getRoleList, createRole, updateRole, getInfo, deleteRole } from '../../../../../apis/backhub/role';
import { message } from 'antd';

class RoleStore {
  roles: Role[] = [];
  modalVisible = false; // 弹窗显示状态
  editingRole: Role | undefined = undefined; // 当前编辑的角色，undefined表示新建
  loading = false;

  constructor() {
    makeAutoObservable(this);
  }

  // 获取角色列表
  fetchRoles = async () => {
    this.loading = true;
    try {
      const response = await getRoleList();
      this.roles = (response as any).data;
    } catch (error) {
      console.error('获取角色列表失败:', error);
    } finally {
      this.loading = false;
    }
  };
  
  // 获取用户
  getRole = async (id: string) => {
    try {
      this.loading = true;
      const response = await getInfo(id);
      this.editingRole =  (response as any).data;
      return this.editingRole; // 返回获取到的用户数据
    } catch (error) {
      console.error('获取用户失败:', error);
      throw error;
    } finally {
      this.loading = false;
    }
  };

  // 显示创建弹窗
  showCreateModal = () => {
    this.editingRole = undefined;
    this.modalVisible = true;
  };

  // 显示编辑弹窗
  showEditModal = (func: Role) => {
    this.editingRole = func;
    this.modalVisible = true;
  };

  // 隐藏弹窗
  hideModal = () => {
    this.modalVisible = false;
    this.editingRole = undefined;
  };

  // 保存角色
  saveRole = async (values: RoleFormValues) => {
    try {
      if (this.editingRole && this.editingRole.id) {
        const response = await updateRole(this.editingRole.id, values);
        if((response as any)?.status){
          message.success('更新成功');
        }
      } else {
        const response = await createRole(values);
        if((response as any)?.status){
            message.success('创建成功');
        }   
      }
      this.hideModal();
      this.fetchRoles();
    } catch (error) {
      console.error('保存角色失败:', error);
    }
  };


  // 删除角色
  deleteRole = async (id: string) => {
    try {
      await deleteRole(id);
      this.fetchRoles();
    } catch (error) {
      console.error('删除角色失败:', error);
    }
  };
}

export const roleStore = new RoleStore();